package com.netcraftsstudio.maven.utility
import groovyx.net.http.RESTClient

import java.security.MessageDigest


class DetermineMavenDependenciesTool {

	/**
	 * 
	 * @param args Directory where .jar files are
	 */
	static main(args) {
		
		if (args.length == 0 || !(new File(args[0]).isDirectory())) {
			
			System.err.println("Usage:  groovy DetermineMavenDependenciesTool aDirectory")
			System.exit(1)			
		}
		
		println()
		println(new DetermineMavenDependenciesTool().execute(args[0]))	
	}
	
		
	String execute(String pathToDirectory) {
		
		def result = new StringBuffer()
		def jarDirectory = new File(pathToDirectory)
		jarDirectory.eachFileMatch(new JarFileFilter(), { file ->			
			def sha1Hash = calculateSha1(file)
			def resultAsDepTrio = getMavenCoordinates(sha1Hash, file.name)
			result.append(resultAsDepTrio)
		})
		return result
	}

	
	/**
	 * Following code was adapted from that on:
	 * http://groovy.codehaus.org/Calculating+a+SHA1+hash+for+large+files 
	 */
	String calculateSha1(File aFile) {
		
		int KB = 1024
		int MB = 1024*KB
		
		def messageDigest = MessageDigest.getInstance("SHA1")
		
		aFile.eachByte(MB) { byte[] buf, int bytesRead ->
		  messageDigest.update(buf, 0, bytesRead);
		}
		
		return new BigInteger(1, messageDigest.digest()).toString(16).padLeft( 40, '0' )
	}
	
	
	String getMavenCoordinates(String sha1Value, String filename) {
		
		def depTrio = new StringBuffer()
		def searchMaven = new RESTClient("http://search.maven.org/solrsearch/select")
		searchMaven.get(query : [q:"1:\"" + sha1Value + "\""]) { response, json ->
			if (response.status == 200) {
				
				// This is useful for parsing JSON (for humans)
				// http://json.parser.online.fr/
				if (json.response.numFound != 0) {
					
					json.response.docs.each {
						depTrio.append("<dependency><groupId>${it.g}</groupId><artifactId>${it.a}</artifactId><version>${it.v}</version></dependency>")
					}
				} else {
					
					System.err.println "Could not locate ${filename} (${sha1Value}) in given Maven repository."
				}				
			} else {
			
				System.err.println "Response of ${response.status} for search request." 
			}
		}
		return depTrio.toString()
	}	
}
